﻿using Furion;
using Furion.DatabaseAccessor;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TulingMember.Application.Dto;
using TulingMember.Core; 
using Yitter.IdGenerator;

namespace TulingMember.Application
{
    public class FinanceService : IDynamicApiController
    {
        private readonly ILogger _logger;
        private readonly IRepository<cts_Finance> _financeRepository;
        private readonly IRepository<cts_FinanceItem> _financeitemRepository; 
        public FinanceService(ILogger<FinanceService> logger
            , IRepository<cts_Finance> financeRepository
             , IRepository<cts_FinanceItem> financeitemRepository)
        {
            _logger = logger;
            _financeRepository = financeRepository;
            _financeitemRepository = financeitemRepository; 
        }


        #region 财务管理
        /// <summary>
        /// 财务列表
        /// </summary> 
        public PagedList<cts_Finance> SearchFinance(BaseInput input)
        {
          
            var search = _financeRepository.AsQueryable();            
            if (!string.IsNullOrEmpty(input.keyword))
            {
                search = search.Where(m => m.FinanceItem.Contains(input.keyword)
                || m.Remark.Contains(input.keyword));
            }
            if (input.type >0)
            {
                search = search.Where(m => m.FinanceItemType == input.type);
            }
            if (input.sdate!=null)
            {
                search = search.Where(m => m.CreatedTime>=input.sdate);
            }
            if (input.edate != null)
            {
                var edate = input.edate?.AddDays(1).Date;
                search = search.Where(m => m.CreatedTime < edate);
            }

            var amount = search.GroupBy(m => m.FinanceItemType).Select(m => new
            {
                FinanceItemType = m.Key,
                Amount = m.Sum(m => m.FinanceAmount),
            }).ToList();


            search = search.OrderByDescending(m=>m.OrderNo);
            var data = search.ToPagedList(input.page, input.size);
            UnifyContext.Fill(amount);
            return data;
        }
        
        /// <summary>
        /// 获取账单详情
        /// </summary> 
        public cts_Finance GetFinance(long id)
        {

           return _financeRepository.FindOrDefault(id);
            
        }
        /// <summary>
        /// 记一笔
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine("finance")]
        [UnitOfWork]
        public Task SaveFinance(cts_Finance input)
        {

            if (input.FinanceItemType != 1 && input.FinanceItemType != 2)
            {
                throw Oops.Bah("类型不正确").StatusCode(ErrorStatus.ValidationFaild);
            }
            if (input.FinanceAmount <=0)
            {
                throw Oops.Bah("金额必须大于0").StatusCode(ErrorStatus.ValidationFaild);
            }
            var item = _financeitemRepository.Where(m => m.Name.Equals(input.FinanceItem)&&m.Type==input.FinanceItemType).FirstOrDefault();
            if (item == null)
            {
                item = new cts_FinanceItem
                {
                    Id = YitIdHelper.NextId(),
                    Name = input.FinanceItem,
                    Type = input.FinanceItemType,
                };
                _financeitemRepository.Insert(item);
            } 
            input.FinanceItemId = item.Id;
            if (input.Id == 0)
            { 
                var today = DateTime.Now.ToString("yyyyMMdd");
                var tenantid = App.User.FindFirst(ClaimConst.TENANT_ID).Value;
                var redisKey = AppStr.FinanceKey + "_" + tenantid + "_" + today;
                var OrderNoIndex= RedisHelper.StringIncrement(redisKey);
                if (OrderNoIndex == 0)
                {
                    OrderNoIndex = RedisHelper.StringIncrement(redisKey);
                }
                input.Id = YitIdHelper.NextId();
                input.OrderNo = today + OrderNoIndex.ToString().PadLeft(3,'0'); 
                _financeRepository.Insert(input);     
            }
            else
            {

                _financeRepository.Update(input);
               

            }
            return Task.CompletedTask;

        }
        /// <summary>
        /// 删除
        /// </summary>  
        [SecurityDefine("finance")]
        public Task DeleteFinance(long id)
        { 
            return _financeRepository.FakeDeleteAsync(id); 
        }
        #endregion

        #region 收支项目
        /// <summary>
        /// 获取收支项目
        /// </summary> 
        public List<cts_FinanceItem> GetFinanceItem(int type)
        {
            var search = _financeitemRepository.AsQueryable();
            if (type > 0)
            {
                search = search.Where(m => m.Type == type);
            }
            search = search.OrderBy(m => m.Name);
            return search.ToList();
        }
        /// <summary>
        /// 保存收支项目
        /// </summary> 
        [SecurityDefine("finance")]
        public Task SaveFinanceItem(cts_FinanceItem input)
        {
            if (input.Id == 0)
            {
               return  _financeitemRepository.InsertAsync(input);
            }
            else {
               return  _financeitemRepository.UpdateAsync(input);
            }
        }
        /// <summary>
        /// 删除收支项目
        /// </summary> 
        [SecurityDefine("finance")]
        public Task DeleteFinanceItem(long id)
        {

           return _financeitemRepository.DeleteAsync(id);
        }
        #endregion

    }
}
